//
//  PhotoBrowserCollectionViewController.swift
//  PhotoBox
//
//  Created by 张明楠 on 14/12/21.
//  Copyright (c) 2014年 张明楠. All rights reserved.
//

import UIKit
import Alamofire
import Haneke
let PhotoBrowserCollectionViewCellIdentifier = "PhotoBrowserCollectionViewCell"
let PhotoBrowserFooterViewIdentifier = "PhotoBrowserFooterView"


class PhotoBrowserCollectionViewController: UICollectionViewController {


    let refreshControl = UIRefreshControl()
    var currentPage = 0
    let pageCount = 21
    let baiduUrl = "http://image.baidu.com/data/imgs"
    var  populatingPhotos = false
    var datas = [String]()

    var end = false
    override func viewDidLoad() {
        super.viewDidLoad()
        //隐藏或者显示导航栏
        //navigationController?.setNavigationBarHidden(true, animated: true)
        setUpView()

        loadData()
        
    }



    func setUpView(){
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        let item = UIBarButtonItem()
        item.title = "返回"
        self.navigationItem.backBarButtonItem = item


        //设置布局样式
        let layout = UICollectionViewFlowLayout()
        let itemWidth = (view.bounds.size.width - 2) / 3
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumInteritemSpacing = 1.0
        layout.minimumLineSpacing = 1.0
        layout.footerReferenceSize = CGSize(width: collectionView!.bounds.size.width, height: 100.0)
        collectionView!.collectionViewLayout = layout

        //设置导航标题
        let titleLabel = UILabel(frame: CGRectMake(0, 0, 60.0, 30.0))
        titleLabel.textColor = UIColor.whiteColor()
        titleLabel.text = "妹子图"
        //设置字体样式
        titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
        self.navigationItem.titleView = titleLabel

        //register cell 
        collectionView?.registerClass(PhotoBrowserCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: PhotoBrowserCollectionViewCellIdentifier)

        collectionView?.registerClass(PhotoBrowserCollectionViewLoadingCell.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: PhotoBrowserFooterViewIdentifier)


        refreshControl.tintColor = UIColor.whiteColor()
        refreshControl.addTarget(self, action: "handleRefresh", forControlEvents: .ValueChanged)
        collectionView!.addSubview(refreshControl)

    }

    func handleRefresh() {
         refreshControl.beginRefreshing()
        //加载数据。
        self.currentPage = 0
        loadData()
        refreshControl.endRefreshing()
    }

    func loadData(){
        if populatingPhotos {
            return
        }
        populatingPhotos = true
        var paraDic = ["col":"美女","tag":"全部","sort":"1","pn":"\(currentPage * pageCount)","rn":"\(pageCount)","p":"channel","from":"1"]
    Alamofire.request(.GET,baiduUrl, parameters:paraDic, encoding: ParameterEncoding.URL).responseJSON { (_, _, JSON, err) -> Void in
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)){
            if JSON != nil {
                var images =   ((JSON as NSDictionary).valueForKey("imgs") as? [NSDictionary])
                println(images?.count)
                if let images = images {
                    let lastItem = self.datas.count
                    for image in images {
                        if image.objectForKey("imageUrl") != nil {
                            self.datas.append(image.objectForKey("imageUrl") as String)
                        }
                    }

                   let indexPaths = (lastItem..<self.datas.count).map{ NSIndexPath(forItem: $0, inSection: 0) }
                    dispatch_async(dispatch_get_main_queue()) {
                        self.collectionView!.insertItemsAtIndexPaths(indexPaths)
         
                        self.currentPage++
                        self.populatingPhotos = false
                    }
                }
            } else {
                self.end = true
            }
    }
    }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //#warning Incomplete method implementation -- Return the number of items in the section

        return self.datas.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCollectionViewCellIdentifier, forIndexPath: indexPath) as PhotoBrowserCollectionViewCell
          cell.imageView.image = nil
        cell.url = self.datas[indexPath.row]
        return cell
    }

    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        var footer = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: PhotoBrowserFooterViewIdentifier, forIndexPath: indexPath) as PhotoBrowserCollectionViewLoadingCell
        footer.isEnd = self.end
        println(">>>>>>")
        return footer as UICollectionReusableView
    }

    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("ShowPhoto", sender: self.datas[indexPath.row])
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ShowPhoto" {
            (segue.destinationViewController as PhotoViewerViewController).imageUrl = (sender as String)
            //隐藏导航栏
            (segue.destinationViewController as PhotoViewerViewController).hidesBottomBarWhenPushed = true
        }
    }



    //刷新指示器
    class PhotoBrowserCollectionViewLoadingCell : UICollectionReusableView {
        var ac = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        var titleLabel = UILabel()
        var isEnd:Bool = false{
            didSet{
                ac.hidden = isEnd
                titleLabel.hidden = !isEnd
            }
        }
        
        override  init(frame: CGRect) {
            super.init(frame: frame)
            titleLabel.text = "没有数据了"
            titleLabel.hidden = true
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = UIColor.whiteColor()
            titleLabel.font = UIFont.boldSystemFontOfSize(CGFloat(20))
            titleLabel.sizeToFit()
            titleLabel.center = CGPointMake(frame.width * 0.5, frame.height * 0.5)
            self.backgroundColor = UIColor.clearColor()
            ac.startAnimating()
            ac.center = CGPointMake(frame.width * 0.5, frame.height * 0.5)
            self.addSubview(ac)
            self.addSubview(titleLabel)
        }

      required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
      }


    }

    //下拉到最底端自动刷新。
    override func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y + scrollView.frame.height > scrollView.contentSize.height {
            loadData()
        }

    }

    //单元格类
    class PhotoBrowserCollectionViewCell : UICollectionViewCell {
        let imageView = UIImageView()

        var url:String?{
            willSet{

                self.imageView.hnk_setImageFromURL(NSURL(string: newValue!)!, placeholder: UIImage(named: "heart"))
                self.imageView.contentMode  = .ScaleToFill

            }
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.imageView.frame = CGRectMake(0, 0, frame.width, frame.height)
            self.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
            self.addSubview(self.imageView)
        }



        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            fatalError("init(coder:) has not been implemented")
        }
    }
}
